var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var bcryptjs = require('bcryptjs');
var { Types: { ObjectId } } = require('mongoose')
var { userModel } = require('../module/user');

/* GET users listing. */
router.post('/reg', async (req, res) => {
    console.log(123)
    let regform = req.body
    let password = bcryptjs.hashSync(regform.password, 12);
    await userModel.create({
        username: regform.username,
        password: password,

    })
    res.send({ code: 201, msg: '注册成功' })
});
//
// 登录接口
router.post('/login', async (req, res) => {
    // 获取前端输入的用户和密码
    console.log(7897);
    let username = req.body.username
    let password = req.body.password
    console.log(username, password);
    // 查询数据库是否有这个用户，如果不存在返回它的长度为0
    let user = await userModel.find({ $or: [{ username: username }] })
    // console.log(user, 'user111');
    if (user.length != 0) {
        let decodepassword = bcryptjs.compareSync(password, user[0].password);
        if (decodepassword) {
            let token = "Bearer " + jwt.sign({ username, password }, "lce", { expiresIn: "1h" })
            console.log(token);
            res.send({
                user: user,
                id: user[0]._id,
                code: 200,
                msg: "登入成功",
                token
            })
        } else {
            res.send({
                code: 400,
                msg: "密码错误!请重新输入!",
            })
        }

    } else {
        res.send({
            code: 400,
            msg: "用户名不存在!",
        })
    }
});

module.exports = router;
